#include "logindialog.h"
#include "ui_logindialog.h"
#include <QtSerialPort/QSerialPortInfo>
#include <QIntValidator>

#include <settingsdialog.h>
#include <colordialog.h>
#include <mainwindow.h>
#include <QSettings>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QtDebug>
#include <QtScript>
#include <QMessageBox>
#include <QApplication>
#include <updatethread.h>

QT_USE_NAMESPACE

static const char blankString[] = QT_TRANSLATE_NOOP("LoginDialog", "N/A");
static const QString settingUsername="2017";
static const QString settingPassword="888888";

LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
    ui->lineEdit_2->setEchoMode(QLineEdit::PasswordEchoOnEdit);//Password
    ui->lineEdit_2->setTextMargins(60,0,0,0);
    ui->lineEdit->setTextMargins(60,0,0,0);

    //ui->lineEdit->setText("1001");
    //ui->lineEdit_2->setText("123456789");
    ui->lineEdit->setText("2017");
    ui->lineEdit_2->setText("888888");

    // 移除标题栏
    this->setWindowFlags(Qt::FramelessWindowHint);

    ui->lineEdit->setFocus();
    wachedLineEdit=ui->lineEdit;

    isRead = false;
    log = new DebugLog();
    log->warnLog("初始化");

    initialConfig();
    qDebug() << url;

    upThread = new UpdateThread();
    connect(upThread, SIGNAL(updateSignal()), this, SLOT(updateApp()));
    upThread->start();

    connect(ui->loginButton, SIGNAL(clicked()),this, SLOT(login()));
    connect(&networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(serviceRequestFinished(QNetworkReply*)));

    ui->lineEdit->installEventFilter(this);
    ui->lineEdit_2->installEventFilter(this);

}

void LoginDialog::updateApp(){
    if(!isRead){
        isRead = true;
        log->writelog("HTTP:" + baseUrl + "/e/system");
        httpRequest.setUrl(QUrl(baseUrl + "/e/system"));
        networkAccessManager.get(httpRequest);
    }
}

// 读取配置信息
bool LoginDialog::readConfig(){

    // 配置文件路径
    QString dir = QCoreApplication::applicationDirPath();
    QString filename = dir + "/EPOS.ini";

    QFile file(filename);
    if (file.exists()) {
        // 读取配置信息
        QSettings settings(filename, QSettings::IniFormat);

        settings.beginGroup("server");
        QString IP = settings.value("serveruri").toString();
        QString port = settings.value("serverport").toString();
        settings.endGroup();

        sysServer = IP;
        sysPort = port;
        baseUrl = "http://" + IP + ":" + port;
        settings.beginGroup("system");
        sysVersion = settings.value("version").toString();
        uptime = settings.value("updatetime").toString();
        settings.endGroup();

        return true;
    }
    else{
        // 找不到配置文件
        return false;
    }
}

void LoginDialog::handlelineeditclicked()
{
    QMessageBox::about(this, "tip", "click");
}

LoginDialog::~LoginDialog()
{
    delete ui;
}

void LoginDialog::initialConfig(){
    // 配置文件路径
    QString dir = QCoreApplication::applicationDirPath();
    QString filename = dir + "/EPOS.ini";
    QFile file(filename);
    QSettings settings(filename, QSettings::IniFormat);
    if (!file.exists()) {
        // 初始配置信息
        settings.beginGroup("server");
        //settings.setValue("serveruri", QVariant("epos.lorytech.com"));
        settings.setValue("serveruri", QVariant("192.168.1.54"));
        settings.setValue("serverport", QVariant("8080"));
        settings.endGroup();
        settings.beginGroup("machine");
        settings.setValue("id", QVariant("EPOS1001"));
        settings.endGroup();
        settings.beginGroup("system");
        settings.setValue("version", QVariant("1.0.0"));
        settings.setValue("name", QVariant("EPOS_V1.0.0"));
        settings.setValue("updatetime", QVariant("24:00"));
        settings.endGroup();
        settings.beginGroup("wifi");
        settings.setValue("name", QVariant("lidatech"));
        settings.setValue("password", QVariant("lidatech"));
        settings.endGroup();
    }
    settings.beginGroup("server");
    QString serveruri = settings.value("serveruri").toString();
    QString serverport = settings.value("serverport").toString();
    settings.endGroup();
    settings.sync();
    url = "http://" + serveruri + ":" + serverport + "/e/login";
    baseUrl = "http://" + serveruri + ":" + serverport;
}

void LoginDialog::login()
{
    ui->label->setText("");
    QString username = ui->lineEdit->text();
    QString password = ui->lineEdit_2->text();
    if(username.length() == 0 || password.length() == 0) {
        this->hide();
        colorDialog->show();
        colorDialog->exec();
        this->show();
        //ui->label->setText("用户名和密码不能为空!");
        return;
    }
    if(username.compare(settingUsername)==0 && password.compare(settingPassword)==0){
        this->hide();
        settingDialog->show();
        settingDialog->initialInfo();
        settingDialog->exec();
        this->show();
    }else{
        httpRequest.setUrl(QUrl(url.toString()+"?username="+username+"&password="+password));
        networkAccessManager.get(httpRequest);
    }
}

void LoginDialog::serviceRequestFinished(QNetworkReply *reply)
{
    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if(reply->error() == QNetworkReply::NoError) {
        QByteArray resultArray=reply->readAll();
        QString result=resultArray;
        QScriptEngine engine;
        QScriptValue sc = engine.evaluate("value="+result);
        if(sc.property("returnCode").toInt32()==200){
            QString r = sc.property("returnType").isNull() ? "0" : "1";
            log->writelog("HTTP Callback:" + r);
            if(!sc.property("returnType").isNull() && sc.property("returnType").toUInt32() == 4){
                QString version = sc.property("version").toString();
                if(readConfig()){
                    if(sysVersion != version){
                        if(!sc.property("file").isNull() && sc.property("file").toString().length() > 0){
                            isRead = false;
                            QString folder = QCoreApplication::applicationDirPath();
                            QString appPath = folder + "/EPOSUpdate.exe -qws";
                            if(QProcess::startDetached(appPath)){
                                exit(0);
                            }
                        }
                        else{
                            log->warnLog("服务器更新应用包不存在");
                        }
                    }
                    else{
                        QString server = sc.property("server").toString();
                        QString port = sc.property("port").toString();
                        if(server.length() > 0 && port.length() > 0){
                            if(server != sysServer || port != sysPort){
                                QString dir = QCoreApplication::applicationDirPath();
                                QString filename = dir + "/EPOS.ini";
                                QSettings settings(filename, QSettings::IniFormat);
                                settings.beginGroup("server");
                                settings.setValue("serveruri", server);
                                settings.setValue("serverport", port);
                                settings.endGroup();
                                settings.sync();
                                sysServer = server;
                                sysPort = port;
                                baseUrl = "http://" + sysServer + ":" + sysPort;

                                settingDialog->initialIniConfig();
                                mainWindow->initialConfig();

                            }
                        }
                    }
                }
                else{
                    log->warnLog("读取应用配置信息失败");
                }
            }
            else{
                QString bcode = sc.property("returnMessage").toString();
                QString dir = QCoreApplication::applicationDirPath();
                QString filename = dir + "/EPOS.ini";
                QSettings settings(filename, QSettings::IniFormat);
                settings.beginGroup("business");
                settings.setValue("code", bcode);
                settings.endGroup();

                //this->hide();
                mainWindow->show();
            }
        }
        else
        {
            ui->label->setText(sc.property("returnMessage").toString());
        }
        //requestFinished(reply, reply->readAll(), statusCode);
    } else {
        //requestFinished(reply, "", statusCode);
        ui->label->setText(reply->errorString());
    }
    reply->deleteLater();
}


void LoginDialog::keyPressEvent(QKeyEvent *event){
    QApplication::beep();
   // qDebug() << "key pressed:" <<hex<< event->key();
    if((event->key()>=Qt::Key_0 )&& (event->key()<=Qt::Key_9)){
        wachedLineEdit->setText(wachedLineEdit->text()+event->key());  
    }else if(event->key()==Qt::Key_Back){
        QString str=wachedLineEdit->text();
        str.chop(1);
        wachedLineEdit->setText(str);
    }else if(event->key()==Qt::Key_Escape){
        ui->lineEdit->setText("");
        ui->lineEdit_2->setText("");
        ui->lineEdit->setFocus();
        wachedLineEdit=ui->lineEdit;
    }else if(event->key()==Qt::Key_Enter){
        if(wachedLineEdit==ui->lineEdit){
            ui->lineEdit_2->setFocus();
            wachedLineEdit=ui->lineEdit_2;
        }else if(wachedLineEdit==ui->lineEdit_2){
            //qDebug() << "login by enter";
            login();
        }
    }
}

bool LoginDialog::eventFilter(QObject *watched, QEvent *event)
{
    if(event->type() == QEvent::MouseButtonPress)
    {
        if(watched == ui->lineEdit)
        {
            wachedLineEdit = ui->lineEdit;
        }
        else if(watched == ui->lineEdit_2)
        {
            wachedLineEdit = ui->lineEdit_2;
        }
    }
    return QWidget::eventFilter(watched,event);     // 最后将事件交给上层对话框
}
